package com.kq.tallybookl.database;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.kq.tallybookl.activity.PreferencesActivity;
import com.kq.tallybookl.item.MenoItem;

import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteException;
import net.sqlcipher.database.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库操作管理类
 * <p>
 * Created by Kq on 2016/4/29.
 */
public class TrueManager {

    private static final String[] COLUMNS = {TrueDBHelper.TITLE_COL,
            TrueDBHelper.TIMESTAMP_COL, TrueDBHelper.DETAILS_COL,};

    private static final String[] COUNT_COLUMN = {"COUNT(1)"};

    private static final String[] ID_COL_PROJECTION = {TrueDBHelper.ID_COL};
    private static final String[] ID_DETAIL_COL_PROJECTION = {TrueDBHelper.ID_COL,
            TrueDBHelper.DETAILS_COL};

    private final Activity activity;

    private String db_key;

    public TrueManager(Activity activity, String key) {
        this.activity = activity;
        db_key = key;
        SQLiteDatabase.loadLibs(activity);
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        try {
            SQLiteDatabase db = helper.getWritableDatabase(db_key);
            db.close();
        } catch (SQLiteException sqliteException) {
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }
    }

    public boolean hasMenoItems() {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(TrueDBHelper.TABLE_NAME, COUNT_COLUMN, null,
                    null, null, null, null);
            cursor.moveToFirst();
            return cursor.getInt(0) > 0;
        } finally {
            close(cursor, db);
        }
    }

    public List<MenoItem> buildMenoItems() {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        List<MenoItem> items = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(TrueDBHelper.TABLE_NAME, COLUMNS, null, null,
                    null, null, TrueDBHelper.TIMESTAMP_COL + " DESC");
            while (cursor.moveToNext()) {
                String title = cursor.getString(0);
                long timestamp = cursor.getLong(1);
                String details = cursor.getString(2);
                items.add(new MenoItem(title, timestamp, details));
            }
        } finally {
            close(cursor, db);
        }
        return items;
    }

    public void deleteMenoItem(MenoItem item) {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(TrueDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    TrueDBHelper.TIMESTAMP_COL + "='" + item.getTimestamp() + "'", null,
                    null, null, TrueDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            db.delete(TrueDBHelper.TABLE_NAME,
                    TrueDBHelper.ID_COL + '=' + cursor.getString(0), null);
        } finally {
            close(cursor, db);
        }
    }

    public void updateMenoItemDetails(MenoItem item, String details) {
        updateMenoItemSingle(item, TrueDBHelper.DETAILS_COL, details);
    }

    public void updateMenoItemTitle(MenoItem item, String title) {
        updateMenoItemSingle(item, TrueDBHelper.TITLE_COL, title);
    }

    public void updateMenoItemTimestamp(MenoItem item, String timestamp) {
        updateMenoItemSingle(item, TrueDBHelper.TIMESTAMP_COL, timestamp);
    }

    public void updateMenoItemSingle(MenoItem item, String update_place, String updata_content) {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(TrueDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    TrueDBHelper.TIMESTAMP_COL + "='" + item.getTimestamp() + "'", null,
                    null, null, TrueDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            ContentValues values = new ContentValues();
            values.put(update_place, updata_content);
            db.update(TrueDBHelper.TABLE_NAME, values,
                    TrueDBHelper.ID_COL + '=' + cursor.getString(0), null);
        } finally {
            close(cursor, db);
        }
    }

    public void updateMenoItem(MenoItem olditem, MenoItem newitem) {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(TrueDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    TrueDBHelper.TIMESTAMP_COL + "='" + olditem.getTimestamp() + "'", null,
                    null, null, TrueDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            ContentValues values = new ContentValues();
            values.put(TrueDBHelper.TITLE_COL, newitem.getTitle());
            values.put(TrueDBHelper.DETAILS_COL, newitem.getDetails());
            values.put(TrueDBHelper.TIMESTAMP_COL, newitem.getTimestamp());
            db.update(TrueDBHelper.TABLE_NAME, values,
                    TrueDBHelper.ID_COL + '=' + cursor.getString(0), null);
        } finally {
            close(cursor, db);
        }
    }

    public void addMenoItem(MenoItem item) {
        ContentValues values = new ContentValues();
        values.put(TrueDBHelper.TITLE_COL, item.getTitle());
        values.put(TrueDBHelper.DETAILS_COL, item.getDetails());
        values.put(TrueDBHelper.TIMESTAMP_COL, item.getTimestamp());

        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase(db_key);
            // Insert the new entry into the DB.
            db.insert(TrueDBHelper.TABLE_NAME, TrueDBHelper.TIMESTAMP_COL, values);
        } finally {
            close(null, db);
        }
    }

    public void clearAll() {
        SQLiteOpenHelper helper = new TrueDBHelper(activity);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase(db_key);
            db.delete(TrueDBHelper.TABLE_NAME, null, null);
        } finally {
            close(null, db);
        }
    }

    private static void close(Cursor cursor, SQLiteDatabase database) {
        if (cursor != null) {
            cursor.close();
        }
        if (database != null) {
            database.close();
        }
    }
}
